Skip to content

如何编程调用OpenAI的ChatGPT API接口

前言

最近大火的ChatGPT并没有官方提供的API接口,github上有码农捣腾出通过无头浏览器获取session的方式编程调用ChatGPT接口,地址Node.js client for the unofficial ChatGPT API. 🔥 (opens new window)

注册一个OpenAI账号

可参考:

中国区注册OpenAI账号试用ChatGPT指南(opens new window)

Node开发环境

Node.js >= 18

这个包是 OpenAI 围绕 ChatGPT 的Node.js 包装程序

您可以使用它开始构建由 ChatGPT 支持的项目,例如聊天机器人、网站等...

12 月 11 日,OpenAI 添加了 Cloudflare 保护,这使得访问非官方 API 变得更加困难。

为了规避这些保护措施,我们添加了一个完全自动化的基于浏览器的解决方案,它在后台使用 Puppeteer 和 CAPTCHA 破解器。🔥

npm install chatgpt puppeteer

puppeteer是一个可选的对等依赖项,用于通过 自动绕过 Cloudflare 保护getOpenAIAuth。主要的 API 包装器fetch直接使用。

import { ChatGPTAPIBrowser } from 'chatgpt'

async function example() {
  // use puppeteer to bypass cloudflare (headful because of captchas)
  const api = new ChatGPTAPIBrowser({
    email: process.env.OPENAI_EMAIL,//openAI账号
    password: process.env.OPENAI_PASSWORD//密码
  })

  await api.initSession()

  const result = await api.sendMessage('Hello World!')
  console.log(result.response)
}

ChatGPT 响应的格式默认为 markdown。如果你想使用纯文本,你可以使用:

const api = new ChatGPTAPIBrowser({ email, password, markdown: false })

如果要跟踪对话,在result对象中使用conversationIdand ,分别messageId传给sendMessageasconversationId和parentMessageId。

const api = new ChatGPTAPIBrowser({ email, password })
await api.initSession()

// send a message and wait for the response
let res = await api.sendMessage('What is OpenAI?')
console.log(res.response)

// send a follow-up
res = await api.sendMessage('Can you expand on that?', {
  conversationId: res.conversationId,
  parentMessageId: res.messageId
})
console.log(res.response)

// send another follow-up
// send a follow-up
res = await api.sendMessage('What were we talking about?', {
  conversationId: res.conversationId,
  parentMessageId: res.messageId
})
console.log(res.response)

有时,ChatGPT 会在开始响应之前挂起很长一段时间。这可能是由于速率限制,也可能是由于 OpenAI 的服务器过载。

为了缓解这些问题,您可以像这样添加超时:

// timeout after 2 minutes (which will also abort the underlying HTTP request)
const response = await api.sendMessage('this is a timeout test', {
  timeoutMs: 2 * 60 * 1000
})

目前该库暂不支持设置代理,所以没法在国内主机运行,只能在国外VPS上部署。

更多详情参考:

https://github.com/transitive-bullshit/chatgpt-api

520608.com 备案号:粤ICP备13053123号